"""
主要的FastAPI应用程序
"""
from fastapi import FastAPI, HTTPException, Depends, UploadFile, File, Form, Request, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import os
import time

from core.config import get_settings, create_directories
from core.database import init_db
from core.logger import setup_logging, api_logger
from core.security import SecurityMiddleware
from services.background_tasks import start_background_tasks, stop_background_tasks
from services.task_scheduler import start_task_scheduler, stop_task_scheduler
from api.auth import auth_router
from api.parse import parse_router
from api.tasks import tasks_router
from api.slicing import slicing_router
from api.admin import admin_router
from api.health import health_router
from api.web import web_router
from api.system import system_router

# 获取配置
settings = get_settings()

# 设置日志
setup_logging()

# 创建必要的目录
create_directories()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时初始化
    api_logger.log_task_event("system", "startup", {"version": settings.app_version})
    
    # 初始化数据库
    init_db()
    
    # 启动后台任务
    start_background_tasks()
    
    # 启动任务调度器
    start_task_scheduler()
    
    yield
    
    # 关闭时清理
    stop_background_tasks()
    stop_task_scheduler()
    api_logger.log_task_event("system", "shutdown")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="基于MinerU的文档解析API服务系统",
    lifespan=lifespan
)

# 添加安全中间件
app.add_middleware(SecurityMiddleware)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=settings.cors_allow_credentials,
    allow_methods=settings.cors_allow_methods,
    allow_headers=settings.cors_allow_headers,
)

# 静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/uploads", StaticFiles(directory=settings.upload_dir), name="uploads")
app.mount("/results", StaticFiles(directory=settings.parsed_results_dir), name="results")

# 请求日志中间件（简化版本，只用于性能监控，不记录详细日志）
@app.middleware("http")
async def log_requests(request: Request, call_next):
    from core.logger import current_request
    
    start_time = time.time()
    
    # 在请求状态中存储请求信息，供装饰器使用
    request.state._request_start_time = start_time
    
    # 将request对象设置到上下文变量中
    token = current_request.set(request)
    
    try:
        response = await call_next(request)
        response_time = time.time() - start_time
        
        # 在响应头中添加处理时间（用于性能监控）
        response.headers["X-Response-Time"] = f"{response_time:.4f}"
        
        return response
        
    except Exception as e:
        response_time = time.time() - start_time
        # 重新抛出异常，让装饰器处理日志记录
        raise
    finally:
        # 清理上下文变量
        current_request.reset(token)


# 全局异常处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    api_logger.log_error(exc, {"endpoint": request.url.path, "method": request.method})
    return JSONResponse(
        status_code=exc.status_code,
        content={"success": False, "message": exc.detail}
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    import traceback
    from datetime import datetime
    
    # 获取请求上下文信息
    request_context = {
        "endpoint": request.url.path,
        "method": request.method,
        "client_ip": request.client.host if request.client else None,
        "user_agent": request.headers.get("user-agent")
    }
    
    # 记录详细异常日志
    api_logger.log_error(exc, request_context)
    
    # 在开发环境下返回详细错误信息，生产环境返回简化信息
    error_detail = {
        "success": False,
        "message": "Internal server error",
        "error_type": type(exc).__name__ if settings.debug else None,
        "timestamp": datetime.now().isoformat()
    }
    
    # 移除None值，保持响应简洁
    error_detail = {k: v for k, v in error_detail.items() if v is not None}
    
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=error_detail
    )


# 注册路由
app.include_router(health_router, prefix="/api/v1", tags=["Health"])
app.include_router(auth_router, prefix="/api/v1/auth", tags=["Authentication"])
app.include_router(parse_router, prefix="/api/v1/parse", tags=["Document Parsing"])
app.include_router(tasks_router, prefix="/api/v1/tasks", tags=["Task Management"])
app.include_router(slicing_router, prefix="/api/v1/slicing", tags=["Document Slicing"])
app.include_router(admin_router, prefix="/api/v1/admin", tags=["Administration"])
app.include_router(system_router, prefix="/api/v1/system", tags=["System Monitor"])
app.include_router(web_router, prefix="/web", tags=["Web Interface"])


@app.get("/")
async def root():
    """根路径重定向到/web"""
    return RedirectResponse(url="/web", status_code=302)


@app.get("/api/v1")
async def api_info():
    """API信息"""
    return {
        "name": settings.app_name,
        "version": settings.app_version,
        "description": "基于MinerU的文档解析API服务系统",
        "endpoints": {
            "auth": "/api/v1/auth",
            "parse": "/api/v1/parse",
            "tasks": "/api/v1/tasks",
            "slicing": "/api/v1/slicing",
            "admin": "/api/v1/admin",
            "health": "/api/v1/health"
        }
    }


if __name__ == "__main__":
    import uvicorn
    
    # 初始化数据库
    init_db()
    
    # SSL配置
    ssl_config = {}
    if settings.ssl_certfile and settings.ssl_keyfile:
        ssl_config = {
            "ssl_certfile": settings.ssl_certfile,
            "ssl_keyfile": settings.ssl_keyfile
        }
    
    # 启动服务器
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower(),
        **ssl_config
    )